package trainer;

import java.util.Map;

import javax.el.ELContext;
import javax.el.ELResolver;
import javax.el.PropertyNotFoundException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIInput;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

@ManagedBean
@SessionScoped
public class loginPanel extends UINamingContainer {

	private UIInput userid;
	private UIInput password;
	private String action;
	private String successOutcome;
	private String failureOutcome;

	public UIInput getUserid() {
		return userid;
	}

	public void setUserid(UIInput userid) {
		this.userid = userid;
	}

	public UIInput getPassword() {
		return password;
	}

	public void setPassword(UIInput password) {
		this.password = password;
	}

	public String action() {
		return action;
	}
	
	public String getSuccessOutcome() {
		return successOutcome;
	}

	public void setSuccessOutcome(String successOutcome) {
		this.successOutcome = successOutcome;
	}

	public String getFailureOutcome() {
		return failureOutcome;
	}

	public void setFailureOutcome(String failureOutcome) {
		this.failureOutcome = failureOutcome;
	}

	public void actionListener(ActionEvent event) {
		FacesContext context = FacesContext.getCurrentInstance();
		FacesMessage message = null;
		ELContext elContext = context.getELContext();
		ELResolver resolver = elContext.getELResolver();
		Map<String, Object> attrs = this.getAttributes();
		Class paramTypes[] = {String.class};
		Object params[] = new Object[1];
		boolean useridIsValid, passwordIsValid;
		
		Object model = attrs.get("model");
		params[0] = getUserid().getValue();
		useridIsValid = (Boolean) resolver.invoke(elContext, model, 
				"useridIsValid", paramTypes, params);
		
		// failureOutcome is not a required attribute
		try {
			action = (String) resolver.getValue(elContext, model, "failureOutcome");
		} catch (PropertyNotFoundException pnfe) {
			action = null;
		}
		
		if (!useridIsValid) {
			message = new FacesMessage("Userid " + params[0].toString() + " is not recognized.");
			context.addMessage(getUserid().getClientId(context), message);
		} else {
			params[0] = getPassword().getValue();
			passwordIsValid = (Boolean) resolver.invoke(elContext, model, 
					"passwordIsValid", paramTypes, params);
			
			if (!passwordIsValid) {
				message = new FacesMessage("Password for userid " + 
						(String) getUserid().getValue() + " is incorrect.");
				context.addMessage(password.getClientId(context), message);
			} else {
				action = (String) resolver.getValue(elContext, model, "successOutcome");
			}
		}
	}
	
	public boolean useridIsValid(String toTest) {
		return false;
	}

	public boolean passwordIsValid(String toTest) {
		return false;
	}

}
